let visitModule = (() => {
  let
    customerId,
    tbody = $('tbody'),
    submit = $('.submit'),
    visitTime = $('.visitTime'),
    visitText = $('.visitText');



  // 渲染回访记录
  let render_visit = async function () {
    let res = await axios.get('/visit/list', { params: { customerId } });
    if (res.code) {
      alert('并无回访记录');
      return;
    }
    // 渲染记录
    let str = ``;
    res.data.forEach(item => {
      str += `
       <tr>
        <td class="w5">${item.id}</td>
        <td class="w15">${item.visitTime}</td> 
        <td class="w70 wrap">${item.visitText}</td>
        <td class="w10" customerId="${item.customerId}" visitId="${item.id}">
          <a href="javascript:;">删除</a>
        </td>
      </tr>
      `
    })
    tbody.html(str)
  }
  // 绑定提交事件
  let handleSubmit = function () {
    let submit_visit = async function () {
      let
        params = {
          customerId,
          visitText: visitText.val(),
          visitTime: visitTime.val()
        },
        res = await axios.post('/visit/add', params);
      !res.code ? (alert('添加回访记录成功'), render_visit()) : alert('添加回访记录失败');
    };
    submit.click(submit_visit)
  }
  // 删除事件
  let handleDelete = function () {
    tbody.click(async ev => {
      let
        target = ev.target,
        visitId = $(target.parentElement).attr('visitId'),
        TAG = target.tagName;
      if (TAG == 'A') {
        let flag = confirm('确定要删除此条回访信息吗');
        if (flag) {
          let res = await axios.get('/visit/delete', { params: { visitId } });
          !res.code ? (alert('删除成功'), render_visit()) : alert('删除失败');
        }
      }
    })
  }
  return {
    init() {
      customerId = window.location.href.getUrlEncodedParams().customerId;
      render_visit();
      handleSubmit();
      handleDelete();
    }
  }
})()

visitModule.init()